package com.education.expenses.eao;

import com.education.expenses.entity.Receipt;
import com.education.expenses.entity.Report;
import com.education.expenses.entity.Role;
import com.education.expenses.entity.User;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * User: alpoloz
 * Date: 7/11/12
 * Time: 6:37 PM
 */
@Repository
public class HibernateUserEAO extends HibernateEAO<User> implements UserEAO {

    @Autowired
    public HibernateUserEAO(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    @Override
    public User getUserByEmail(String email) {
        Criteria criteria = super.getCurrentSession().createCriteria(User.class).setMaxResults(1);
        criteria.add(Restrictions.eq("email", email));
        return (User) criteria.uniqueResult();
    }

    @Override
    public Report getWeekReport(Long id, Date reportDate) {
        Criteria criteriaReport = super.getCurrentSession().createCriteria(User.class);
        criteriaReport.add(Restrictions.eq("id", id))
                .setFetchMode("reports", FetchMode.JOIN)
                .add(Restrictions.eq("date_report", new SimpleDateFormat("dd/MM/yyyy").format(reportDate)));

        Report report = (Report) criteriaReport.uniqueResult();
        return report;
    }

    @Override
    public List<Receipt> getWeekReceiptListUser(Long id, Date reportDate, int pageNumber, int pageSize) {

        Report report = getWeekReport(id, reportDate);

        Criteria criteriaReceipts = super.getCurrentSession().createCriteria(Report.class)
                .setFetchMode("report_id", FetchMode.JOIN)
                .add(Restrictions.eq("report_id", report.getId()))
                .setFirstResult(pageSize * (pageNumber - 1))
                .setMaxResults(pageSize);

        List<Receipt> listReceipts = criteriaReceipts.list();
        return listReceipts;
    }

    @Override
    public boolean isUsersExist() {
        Criteria criteria = super.getCurrentSession().createCriteria(User.class).setMaxResults(1);

        if (criteria.list().isEmpty()) {
            return false;
        }
        return true;
    }

    @Override
    public List<User> getUsersByRole(Role role){
        Criteria criteria = super.getCurrentSession().createCriteria(User.class);
        criteria.add(Restrictions.eq("role", role));
        List<User> list = criteria.list();
        return list;
    }

}

